import "dart:convert";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/lock_result/index.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/state/common.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/utils/storage.dart";
import "package:ct_pa_majordomo/widgets/empty_data/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:provider/provider.dart";
import "package:ttlock_flutter/ttlock.dart";

class NearLock extends StatefulWidget {
  final String lockName;
  const NearLock({super.key, required this.lockName});

  @override
  State<StatefulWidget> createState() => _NearLockState();

}
class _NearLockState extends State<NearLock> {

  List<TTLockScanModel> _lockList = [];
  late String _lockData;
  bool _scanning = true;
  int? _apartmentId;

  @override
  void initState() {
    super.initState();
    _startScanLock();
  }

  @override
  void dispose() {
    super.dispose();
    print("停止扫描锁");
    // if (_lockData != null) TTLock.resetLock(_lockData, () {}, (errorCode, errorMsg) {});
    _endScanLock();
  }

  void _startScanLock() async {
    _lockList = [];
    TTLock.getBluetoothState((state) {
      print("回调：$state");
      if (state == TTBluetoothState.turnOn) {
        print("开始搜索");
        TTLock.startScanLock((scanModel) {
          setState(() {
            _scanning = true;
          });
          bool contain = false;
          bool initStateChanged = false;
          for (var model in _lockList) {
            if (scanModel.lockMac == model.lockMac) {
              contain = true;
              initStateChanged = model.isInited != scanModel.isInited;
              if (initStateChanged) {
                model.isInited = scanModel.isInited;
              }
              break;
            }
          }
          if (!contain) {
            _lockList.add(scanModel);
          }
          if (!contain || initStateChanged) {
            setState(() {
              _lockList.sort((model1, model2) =>
              (model2.isInited ? 0 : 1) - (model1.isInited ? 0 : 1));
            });
          }
        });
      }
    });
  }

  void _initLock(TTLockScanModel scanModel) async {
    EasyLoading.show();

    Map map = Map();
    map["lockMac"] = scanModel.lockMac;
    map["lockVersion"] = scanModel.lockVersion;
    map["isInited"] = scanModel.isInited;
    TTLock.initLock(map, (lockData) async {
      setState(() {
        _lockData = lockData;
      });
      Map<String, dynamic> params = {
        "lockData": lockData,
        "lockAlias": widget.lockName,
        "apartmentId": _apartmentId,
        "lockName": widget.lockName,
      };
      print("成功：>>>>>>>>>>> $params");
      Map resData = await lockApi.initLock(params);
      EasyLoading.showSuccess("门锁添加成功");
      print("成功：>>>>>>>>>>> $lockData");
      // 设置远程开锁开关
      TTLock.setLockRemoteUnlockSwitchState(true, lockData, (msg) {
        print(msg);
      }, (errorCode, errorMsg) {
        EasyLoading.showError("$errorCode: $errorMsg");
        print("$errorCode: $errorMsg");
      });
      Stacker.pushNamed(Keys.DEVICE_LOCK_ADD_LOCK_RESULT, arguments: resData["data"]);
      // Navigator.push(context,
      //   CupertinoPageRoute(builder: (BuildContext context) {
      //     return LockResult(lockData: lockData);
      //   })
      // );
    }, (errorCode, errorMsg) {
      EasyLoading.dismiss();
    });
  }


  void _endScanLock() async {
    TTLock.stopScanLock();
  }


  @override
  Widget build(BuildContext context) {
    _apartmentId = jsonDecode(storage.getString("apartment") ?? "")?["apartmentId"];
    return Scaffold(
      appBar: AppBar(
        iconTheme: const IconThemeData(color: Colors.white),
        title: const Text("附近的锁", style: TextStyle(color: Colors.white),),
        centerTitle: true,
        backgroundColor: ThemeVars.colorPrimaryDark,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        actions: [
          if (_scanning) Container(
            height: 16,
            width: 16,
            margin: EdgeInsets.only(right: 12),
            child: const CircularProgressIndicator(
              strokeWidth: 2,
              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
            ),
          )
        ],
      ),
      body: Column(
        children: [
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(12),
            color: Colors.amber[50],
            child: const Text(
              "提示：添加时请摸亮门锁密码键盘",
              style: TextStyle(color: Colors.orange),
            ),
          ),
          Expanded(
            child: _lockList.isEmpty
              ? EmptyData()
              : ListView.separated(
                padding: const EdgeInsets.all(ThemeVars.paddingPage),
                itemBuilder: (context, index) {

                  TTLockScanModel scanModel = _lockList[index];

                  return DecoratedBox(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(6),
                      boxShadow: const [ThemeVars.boxShadow],
                      color: Colors.white,
                    ),
                    child: Container(
                      padding: const EdgeInsets.all(16),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(scanModel.lockName ?? "--", style: const TextStyle(fontSize: 18),),
                          if (!scanModel.isInited) IconButton(
                            icon: const Icon(Icons.add, color: ThemeVars.colorPrimary,),
                            onPressed: () {
                              if (!scanModel.isInited) {
                                TTLock.stopScanLock();
                                setState(() {
                                  _scanning = false;
                                });
                                _initLock(scanModel);
                              }
                            },
                          ),
                        ],
                      ),
                    ),
                  );
                },
                separatorBuilder: (context, index) => const SizedBox(height: 12),
                itemCount: _lockList.length,
              ),
          ),
        ],
      ),
    );
  }
}